package com.example.netty;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private static final String SERVER_IP = "192.168.3.39";
    private static final int SERVER_PORT = 9999;

    //实现跳转
    private Button mBtControl;
    private Button mBtGetdata;

    //以下为各个实时数据的命名
    private TextView mTvTemperature;
    private TextView mTvHumidity;
    private TextView mTvIll;
    private TextView mTvFan;
    private TextView mTvInfrared;
    private TextView mTvRedlight;
    private TextView mTvYellowlight;
    private TextView mTvGreenlight;


    private Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //实现跳转
        mBtControl = findViewById(R.id.control_page);
        mBtControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
                intent = new Intent(MainActivity.this,ControlActivity.class);
                startActivity(intent);
            }
        });

        mBtGetdata = findViewById(R.id.getdata);
        mTvTemperature = findViewById(R.id.temperature);
        mTvHumidity = findViewById(R.id.humidity);
        mTvIll = findViewById(R.id.ill);
        mTvFan = findViewById(R.id.fan);
        mTvInfrared = findViewById(R.id.infrared);
        mTvRedlight = findViewById(R.id.redlight);
        mTvYellowlight = findViewById(R.id.yellowlight);
        mTvGreenlight = findViewById(R.id.greenlight);



        //获取数据
        mBtGetdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new FetchDataFromServerTask().execute();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            // 关闭连接
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class FetchDataFromServerTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            String message = "";
            try {
                // 创建Socket对象，连接服务器
                socket = new Socket(SERVER_IP, SERVER_PORT);

                // 获取输出流，向服务器发送数据
                OutputStream outputStream = socket.getOutputStream();
                InputStream inputStream = socket.getInputStream();
                String requestData = "front-end:String=apple";
                outputStream.write(requestData.getBytes());

                byte[] buffer = new byte[1024];
                int length = inputStream.read(buffer);
                message = new String(buffer, 0, length);
                System.out.println("接收到服务器的消息：" + message);

                // 关闭连接（注意：保持连接时请勿关闭）
                socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return message;
        }

        @Override
        protected void onPostExecute(String message) {
            super.onPostExecute(message);
            updateUiWithMessage(message);
        }
    }

    private void updateUiWithMessage(String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 将服务器返回的数据按逗号分隔成字符串数组
                String[] dataArray = message.split(",");

                String temperature = dataArray[0];
                String humidity = dataArray[1];
                String ill = dataArray[2];
                String fan = dataArray[3];
                String infrared = dataArray[4];
                String redlight = dataArray[5];
                String yellowlight = dataArray[6];
                String greenlight = dataArray[7];

                mTvTemperature.setText(temperature);
                mTvHumidity.setText(humidity);
                mTvIll.setText(ill);
                mTvFan.setText(fan);
                mTvInfrared.setText(infrared);
                mTvRedlight.setText(redlight);
                mTvYellowlight.setText(yellowlight);
                mTvGreenlight.setText(greenlight);
            }
        });
    }
}
